//
//  NSObject+ACExt.m
//  ACFramework
//
//  Created by caoyq on 2018/11/22.
//

#import "NSObject+ACExt.h"

@implementation NSObject (ACExt)

- (UIViewController *)ac_currentViewController
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * temp in windows)
        {
            if (temp.windowLevel == UIWindowLevelNormal)
            {
                window = temp;
                break;
            }
        }
    }
    
    //window确认 找下一个响应视图
    id  nextResponder = nil;
    
    UIViewController *appRootVC = window.rootViewController;
    //如果是present出来的，appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController)
    {
        nextResponder = appRootVC.presentedViewController;
    }
    else
    {
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]])
    {
        UITabBarController *tabbar = (UITabBarController *)nextResponder;
        UINavigationController *nav = (UINavigationController *)tabbar.selectedViewController;
        result = nav.childViewControllers.lastObject;
    }
    else if ([nextResponder isKindOfClass:[UINavigationController class]])
    {
        UIViewController * fatherNavc = (UIViewController *)nextResponder;
        result = fatherNavc.childViewControllers.lastObject;
    }
    else
    {
        result = nextResponder;
    }
    
    return result;
}

+ (BOOL)ac_isEmptyWithObject: (id)object
{
    if ([object isKindOfClass:[NSString class]]) {
        NSString *obj = (NSString *)object;
        if (obj.length > 0) {
            return NO;
        }
    }else if ([object isKindOfClass:[NSArray class]]) {
        NSArray *ary = (NSArray *)object;
        if (ary.count > 0) {
            return NO;
        }
    }else if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)object;
        if (dic.allKeys.count > 0) {
            return NO;
        }
    }
    return YES;
}

- (NSString *)ac_jsonPrettyStringEncoded
{
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        if (!error) return json;
    }
    return nil;
}

@end
